/*
 * Connector.java
 * this file is the helper tool for client-side application dev. client-side dev doesn't have know
 * how to set up a socket with server-side application. Dev only needs to edit the clientconfig.xml,
 * which specifies the controller's URL and then get the socket from initialize a Connector and
 * call the getSocket.
 * All the message sending, receiving, parsing, and connecting are encapsulated in this file
 * 
 * */

package wps.servicebus.client;

import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;

import org.apache.commons.cli.BasicParser;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.apache.xerces.parsers.DOMParser;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class Connector {
	static Logger logger = Logger.getLogger(Connector.class);
	public static String RootPath=".\\";
	public static String ConfigPath = RootPath + "config\\";
	public static String ConfigFilePath = ConfigPath + "clientconfig.xml";
	private Socket socket = null;
	private String name;
	private String address;
	private int port = 0;
	public Connector(){
		DOMParser parser = new DOMParser();
		try {
			parser.parse(ConfigFilePath);
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Document doc = parser.getDocument();
		name = getRootNode(doc, "name").getChildNodes().item(0).getNodeValue();
		address = getRootNode(doc, "address").getChildNodes().item(0).getNodeValue();
		port = Integer.parseInt(getRootNode(doc, "port").getChildNodes().item(0).getNodeValue());
		logger.debug("name:"+name);
		logger.debug("address:"+address);
		logger.debug("port:"+port);
		
		HttpClient httpclient = new DefaultHttpClient();
		HttpGet httpget = new HttpGet(getURL());		
		HttpResponse res = null;
		String message = "";
		try {
			res = httpclient.execute(httpget);
			HttpEntity entity = res.getEntity();
			message = EntityUtils.toString(entity);
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		Options opt = new Options();        
        opt.addOption("addr", true, "address");
        opt.addOption("port", true, "port");        
                
        String[] arg = message.split(" ");
        BasicParser bparser = new BasicParser();
        CommandLine cl = null;
		try {
			cl = bparser.parse(opt, arg);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        
        String URL = cl.getOptionValue("addr");
        int port = Integer.parseInt(cl.getOptionValue("port"));
        try {
			socket = new Socket(URL, port);
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}		
	}
	
	private Element getRootNode(Document doc, String qname) {
		Node root = doc.getElementsByTagName("connection").item(0);		
		NodeList nodes = root.getChildNodes();
		Element result = null;
		for(int i = 0; i < nodes.getLength(); i++){
			if(nodes.item(i).getNodeName().equals(qname)){
				result = (Element)nodes.item(i);
			}
		}
		if(result == null){
			logger.error("There is no " + qname + " defined!");
		}
		return result;
	}
	public Socket getSocket(){
		return socket;		
	}
	private String getURL(){
		return "http://"+address+":"+port+"/start";
	}
	
	public static void main(String[] args){
		Connector con = new Connector();
	}
}
